import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';

import ECharts from '@kuiper-components/echarts';

import { percent } from '../../../../../../common/formatter';
import s from './style.module.css';

const option = {
	title: {
		text: '网站状态',
		top: 'middle',
		left: '29%',
		textAlign: 'center',
		textStyle: {
			fontSize: 14,
			fontWeight: 'normal',
		},
	},
	tooltip: {
		confine: true,
		trigger: 'item',
		formatter: '{b} : {c} ({d}%)',
	},
	legend: {
		type: 'scroll',
		orient: 'vertical',
		left: '54%',
		top: 'middle',
		itemGap: 20,
		icon: 'circle',
		data: ['异常', '正常'],
	},
	series: {
		type: 'pie',
		radius: ['60%', '80%'],
		center: ['30%', '50%'],
		label: {
			normal: {
				show: false,
				position: 'outside',
			},
			emphasis: {
				show: false,
				textStyle: {
					fontSize: '20',
					fontWeight: 'normal',
				},
			},
		},
		labelLine: {
			normal: {
				show: false,
			},
			emphasis: {
				show: false,
			},
		},
	},
};

function CountsPieChart({ className, abnormalCounts, total }) {
	const data = [
		{
			name: '异常',
			value: abnormalCounts,
		},
		{
			name: '正常',
			value: total - abnormalCounts,
		},
	];
	option.series.data = data;

	const percentMap = data.reduce((obj, { name, value }) => {
		obj[name] = percent(value / total || 0);
		return obj;
	}, {});
	option.legend.formatter = name => {
		return `${name}：${percentMap[name]}`;
	};

	return <ECharts className={cn(className, s.levelCount)} option={option} />;
}

CountsPieChart.propTypes = {
	className: PropTypes.string,
	abnormalCounts: PropTypes.number.isRequired,
	total: PropTypes.number.isRequired,
};
CountsPieChart.defaultProps = {
	className: s.levelCount,
	abnormalCounts: 0,
	total: 0,
};

export default CountsPieChart;
